package com.shxy.cloudclassroom.controller.admin;

import com.shxy.cloudclassroom.entity.dto.EditUserDTO;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.entity.vo.AdminDashboardVO;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

/**
 * @Author 吴汇明
 * @School 绥化学院
 * @CreateTime 2025.10.20
 * 管理员模块
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;
    @Resource
    private LearningResourceService learningResourceService;
    @Resource
    private AssignmentService assignmentService;
    @Resource
    private AssignmentSubmissionService assignmentSubmissionService;
    @Resource
    private ForumPostService forumPostService;
    @Resource
    private ForumReplyService forumReplyService;
    @Resource
    private MajorService majorService;
    @Resource
    private OssService ossService;
    @Resource
    private DownloadHistoryService downloadHistoryService;
    @Resource
    private ViewHistoryService viewHistoryService;

    /**
     * 管理员主页面
     */
    @GetMapping("/index")
    public String index(HttpSession session, Model model) {
        AdminDashboardVO adminDashboardVO = adminService.getAdminIndexData(session, userService, learningResourceService,
                assignmentService, forumPostService, forumReplyService, majorService);
        
        if (adminDashboardVO == null) {
            return "redirect:/login";
        }
        model.addAttribute(USERS, adminDashboardVO.getUsers());
        model.addAttribute(ADMINS, adminDashboardVO.getAdmins());
        model.addAttribute(RESOURCES, adminDashboardVO.getResources());
        model.addAttribute(ASSIGNMENTS, adminDashboardVO.getAssignments());
        model.addAttribute(FORUMS, adminDashboardVO.getForums());
        model.addAttribute(REPLIES, adminDashboardVO.getReplies());
        model.addAttribute(USER_MAP, adminDashboardVO.getUserMap());
        model.addAttribute(MAJOR_MAP, adminDashboardVO.getMajorMap());
        model.addAttribute(POST_MAP, adminDashboardVO.getPostMap());
        return "admin/index";
    }

    /**
     * 更新用户头像
     */
    @PostMapping("/uploadAvatar")
    @ResponseBody
    public Map<String, Object> updateAvatar(@RequestParam("avatar") MultipartFile file, HttpSession session) {
        return adminService.updateAvatar(file, session, ossService, userService);
    }

    /**
     * 添加用户为管理员
     */
    @PostMapping("/users/promote")
    @ResponseBody
    public Map<String, Object> promoteToAdmin(@RequestParam("userId") Long userId) {
        return adminService.promoteToAdmin(userId, userService);
    }

    /**
     * 根据id实现逻辑删除用户
     *
     * @param id 用户ID
     */
    @DeleteMapping("/users/{id}")
    @ResponseBody
    public Map<String, Object> delUserById(@PathVariable Long id, HttpSession session) {
        return adminService.delUserById(id, session, userService);
    }

    @PostMapping("/users")
    @ResponseBody
    public Map<String, Object> updateUser(@RequestBody EditUserDTO editUserDTO, HttpSession session) {
        return adminService.updateUser(editUserDTO, session, userService);
    }

    /**
     * 将管理员降级为普通用户(仅超级管理员可用)
     */
    @PutMapping("/admins/demote/{userId}")
    @ResponseBody
    public Map<String, Object> demoteToUser(@PathVariable("userId") Long userId, HttpSession session) {
        return adminService.demoteToUser(userId, session, userService);
    }

    /**
     * 将普通用户提升为管理员（仅超级管理员可用）
     */
    @PostMapping("/admins/promote")
    @ResponseBody
    public Map<String, Object> promoteUserToAdmin(@RequestParam("userId") Long userId) {
        return adminService.promoteUserToAdmin(userId, userService);
    }

    /**
     * 根据id逻辑删除管理员(仅超级管理员可用)
     *
     * @param id 管理员id
     * @return 响应数据
     */
    @DeleteMapping("/admins/{id}")
    @ResponseBody
    public Map<String, Object> delAdminById(@PathVariable Long id, HttpSession session) {
        return adminService.delAdminById(id, session, userService);
    }

    /**
     * 删除学习资源
     */
    @DeleteMapping("/resources/{resourceId}")
    @ResponseBody
    public Map<String, Object> deleteResource(@PathVariable("resourceId") Long resourceId) {
        return adminService.deleteResource(resourceId, downloadHistoryService, viewHistoryService,
                assignmentService, assignmentSubmissionService, learningResourceService);
    }

    @GetMapping("/resources/{id}")
    @ResponseBody
    public Map<String, Object> getResource(@PathVariable Long id) {
        return adminService.getResource(id, majorService, learningResourceService);
    }

    /**
     * 添加作业或考试
     */
    @PostMapping("/assignments")
    @ResponseBody
    public Map<String, Object> addAssignment(
            @RequestParam("title") String title,
            @RequestParam("majorId") Integer majorId,
            @RequestParam("description") String description,
            @RequestParam("deadline") String deadline,
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpSession session) {
        return adminService.addAssignment(title, majorId, description, deadline, file, session, ossService, assignmentService);
    }

    /**
     * 删除作业或考试
     */
    @DeleteMapping("/assignments/{assignmentId}")
    @ResponseBody
    public Map<String, Object> deleteAssignment(@PathVariable("assignmentId") Long assignmentId) {
        return adminService.deleteAssignment(assignmentId, assignmentSubmissionService, assignmentService);
    }

    /**
     * 获取作业提交列表
     */
    @GetMapping("/assignments/{assignmentId}/submissions")
    @ResponseBody
    public Map<String, Object> getAssignmentSubmissions(@PathVariable("assignmentId") Long assignmentId) {
        return adminService.getAssignmentSubmissions(assignmentId, assignmentSubmissionService);
    }

    /**
     * 批改作业
     */
    @PostMapping("/assignments/submissions/{submissionId}/grade")
    @ResponseBody
    public Map<String, Object> gradeSubmission(
            @PathVariable("submissionId") Long submissionId,
            @RequestParam("score") BigDecimal score,
            @RequestParam("comment") String comment) {
        return adminService.gradeSubmission(submissionId, score, comment, assignmentSubmissionService);
    }

    /**
     * 是否置顶帖子
     */
    @PostMapping("/posts/{postId}/top/{isTop}")
    @ResponseBody
    public Map<String, Object> topPost(@PathVariable("postId") Long postId,
                                       @PathVariable("isTop") Integer isTop) {
        return adminService.topPost(postId, isTop, forumPostService);
    }

    /**
     * 是否加精帖子
     */
    @PostMapping("/posts/{postId}/highlight/{isElite}")
    @ResponseBody
    public Map<String, Object> highlightPost(@PathVariable("postId") Long postId,
                                             @PathVariable("isElite") Integer isElite) {
        return adminService.highlightPost(postId, isElite, forumPostService);
    }

    /**
     * 取消加精帖子
     */
    @PostMapping("/posts/{postId}/unhighlight")
    @ResponseBody
    public Map<String, Object> unhighlightPost(@PathVariable("postId") Long postId) {
        return adminService.unhighlightPost(postId, forumPostService);
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/posts/{postId}")
    @ResponseBody
    public Map<String, Object> deletePost(@PathVariable("postId") Long postId) {
        return adminService.deletePost(postId, forumReplyService, forumPostService);
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/replies/{replyId}")
    @ResponseBody
    public Map<String, Object> deleteReply(@PathVariable("replyId") Long replyId) {
        return adminService.deleteReply(replyId, forumReplyService);
    }
}